/**
 * 作者: sessionliang
 * 时间: 2018-10-24
 * 描述:  购买学时选择页面
 */
define(function(require, exports, module) {
	"use strict";
	//每一个页面都要引入的工具类
	var CommonTools = require('CommonTools_Core');
	var WindowTools = require('WindowTools_Core');
	var StorageTools = require('StorageTools_Core');

	//base service
	var baseService = require('Base_Service');
	var trainService = require('Train_Service');

	var enumHelper = require('Common_Enum');
	//user info
	var userInfo;

	//下拉刷新基类
	var pullToRefreshBase;
	//skin-默认为default
	var skin = 'default';
	//下拉刷新对象
	var pullToRefresh;
	//以下几个是测试加载更多,没有更多数据功能的
	//当前页
	var currpage = 0;
	//每页大小
	var pageSize = 10;
	// initready 要在所有变量初始化做完毕后
	CommonTools.initReady(initData);
	/**
	 * @description 初始化数据,结合initReady使用
	 * plus情况为plusready
	 * 其它情况为直接初始化
	 */
	function initData() {
		skin = WindowTools.getExtraDataByKey('skin') || skin;
		//引入必备文件,下拉刷新依赖于mui与mustache
		CommonTools.importFile([
			'js/libs/mui.min.js',
			'js/libs/mustache.min.js'
		], function() {
			userInfo = StorageTools.getStorageItem(baseService.UserInfoKey);
			initPullToRefreshBySkin(skin);
			tozizhu();
		});

	}
	
	function tozizhu(){
		mui('.mui-scroll').on('tap','#zizhu',function(){
			
			WindowTools.createWin(null,'../apply/zizhu_apply_select.html', null, {},function(){
				console.log("aaaa");
				
			});
			if(plus){
				plus.webview.currentWebview().parent().close();
			}
		});
	}
	
	/**
	 * @description 初始化时通过skin来决定使用哪一种下拉刷新
	 * 注意；初始化下拉刷新请在初始化时使用,重复使用无效
	 * 这里面是异步引入
	 * @param {String} skin
	 */
	function initPullToRefreshBySkin(skin) {
		var generatePullToRefreshCallback = function(targetPullToRefresh) {
			pullToRefreshBase = targetPullToRefresh;
			initPullRefreshList();
		};
		if(skin === 'default') {
			require.async('PullToRefresh_Base_Default_Core', generatePullToRefreshCallback);
		} else if(skin === 'type0') {
			require.async('PullToRefresh_Base_Type0_Core', generatePullToRefreshCallback);
		} else {
			//其它皮肤都需要引入css
			CommonTools.importFile('css/RayApp/RayApp.PullToRefresh.css');
			if(skin === 'type1') {
				require.async('PullToRefresh_Base_Type1_Core', generatePullToRefreshCallback);
			} else if(skin === 'type1_material1') {
				require.async('PullToRefresh_Base_Type1__Material1_Core', generatePullToRefreshCallback);
			} else {
				console.error("错误:传入的下拉刷新皮肤错误,超出范围!");
			}
		}

	}
	/**
	 * @description 测试添加数据
	 * 真实情况添加的数据要根据接口返回数据映射
	 * @param {Number} count 数量
	 * @param {Boolean} isPullDown 是否是下拉刷新
	 */
	function appendData(count, isPullDown) {
		isPullDown = isPullDown || false;
		var fragment = document.createDocumentFragment();
		var offset = (currpage-1)*pageSize;
		trainService.getTrainGoods(offset, pageSize, function(retval) {
			debugger;
			for(var i = 0; i < retval.length; i++) {
				var item = retval[i];
				var li;
				li = document.createElement('li');
				li.className = 'mui-table-view-cell mui-media';
				li.setAttribute("data-id", item.GoodID);
				li.setAttribute("data-driving-title", item.DrivingTitle);
				li.setAttribute("data-place-name", item.PlaceName);
				li.setAttribute("data-driving-license-type", item.DrivingLicenseType);
				li.setAttribute("data-time-solt-type", item.TimeSoltType);
				li.setAttribute("data-course-type", item.CourseType);
				li.setAttribute("data-price", item.Price);
				
				li.innerHTML = '<a href="javascript:;" class="">'
								+ '<div class="mui-table-view-cell-title-container">'
								+ '<span class="mui-table-view-cell-title">'+item.GoodName+'</span>'
								+ '<p class="mui-table-view-cell-sub-title">类型:'+enumHelper.drivingLicenseTypeFormat(item.DrivingLicenseType)+','
								+ '<span class="mui-table-view-cell-sub-title">课时类型:'+enumHelper.subjectTypeFormat(item.SubjectType)+'</span>'
								+ '<span class="mui-table-view-cell-sub-title">,时段:'+enumHelper.timeSoltTypeFormat(item.TimeSoltType)+'</span></p>'
								+ '</div>'
								+ '<div class="mui-table-view-cell-title-container">'
								+ '<span class="mui-table-view-cell-sub-title">'+item.PlaceName+'</span>'
								
								+ '</div>'
								+ '<div class="mui-pull-left custome-table-cell-left">'
								+ '<img style="max-width:100%;width:100%;height:60px;" class="mui-media-object mui-pull-left" src="'+baseService.getImg(item.Picture, 'good')+'">'
								+ '</div>'
								+ '<div class="mui-media-body mui-pull-right">'
								+ '学车费用：<span class="custome-amount-2">'+item.Price+'元/学时</span>'
								+ '<p class="mui-table-view-cell-remark" style="margin-bottom:5px;"></p>'
								+ '<button type="button" class="mui-btn mui-btn-danger mui-pull-right">加入购物车</button>'
								+ '</div>'
								+ '</a>';
				
				fragment.appendChild(li);
			}
			var dataContainer = document.getElementById('listdata');
			//添加-下拉刷新时先清除数据
			if(isPullDown) {
				dataContainer.innerHTML = '';
			}
			dataContainer.appendChild(fragment);
			initListeners();
			resetState(isPullDown, retval.length);
		}, function() {
			resetState(true, 0);
		});
	}

	/**
	 * @description 监听
	 */
	function initListeners() {
		mui("#listdata").off("tap", "li.mui-table-view-cell button").on("tap", "li.mui-table-view-cell button", function() {
			if(userInfo==null){
				closeAllPage('../account/login.html');
				return;
			}
			var id = this.parentElement.parentElement.parentElement.getAttribute("data-id");
			var drivingTitle = this.parentElement.parentElement.parentElement.getAttribute("data-driving-title");
			var placeName = this.parentElement.parentElement.parentElement.getAttribute("data-place-name");
			var drivingLicenseType = this.parentElement.parentElement.parentElement.getAttribute("data-driving-license-type");
			var timeSoltType = this.parentElement.parentElement.parentElement.getAttribute("data-time-solt-type");
			var courseType = this.parentElement.parentElement.parentElement.getAttribute("data-course-type");
			var price = this.parentElement.parentElement.parentElement.getAttribute("data-price");
			WindowTools.createWin(null, "train_add.html", {
				'goodId': id,
				'drivingTitle': drivingTitle,
				'placeName': placeName,
				'drivingLicenseType': drivingLicenseType,
				'timeSoltType': timeSoltType,
				'price': price,
				'courseType': courseType
			}, {});
		});
	}
	
	function closeAllPage(url) {
		if(mui.os.ios){
			var curr = plus.webview.currentWebview();
			var wvs = plus.webview.all();
			for(var i = 0, len = wvs.length; i < len; i++) {
				//关闭除setting页面外的其他页面
				if(wvs[i].getURL() == curr.getURL())
					continue;
				plus.webview.close(wvs[i]);
			}
			plus.webview.open(url);
			curr.close();
		}else{
			var style = {};
			WindowTools.createWin(null, url, null, style);
		}
		
	}

	/**
	 * @description 重置状态
	 * @param {Boolean} isPullDown 是否是上拉加载
	 */
	function resetState(isPullDown, returnDataCount) {
		if(isPullDown) {
			pullToRefresh.endPullDownToRefresh();
			pullToRefresh.refresh();
		} else {
			if(returnDataCount >= pageSize) {
				pullToRefresh.endPullUpToRefresh(false);
			} else {
				pullToRefresh.endPullUpToRefresh(true);
			}
		}
	}
	
	/**
	 * @description 初始化下拉刷新
	 * 这时候,基类对象已经可以了
	 */
	function initPullRefreshList() {

		var pullUpRefreshCallback = function() {
			var self = this;
			console.log("pull up");
			//当前页++
			currpage++;
			appendData(pageSize, false);
		};
		var pullDownRefreshCallback = function() {
			var self = this;
			console.log("pull down");
			currpage = 1;
			appendData(pageSize, true);
			
		};
		var element = '#pullrefresh';

		//初始化下拉刷新
		pullToRefresh = pullToRefreshBase.initPullToRefresh({
			//下拉有关
			down: {
				callback: pullDownRefreshCallback,
			},
			//down为null表示不要下拉刷新
			//down: null,
			//上拉有关
			up: {
				//是否自动上拉加载-初始化是是否自动
				auto: true,
				//距离底部高度(到达该高度即触发)
				offset: 100,
				//是否隐藏那个加载更多动画,达到默认加载效果
				show: true,
				callback: pullUpRefreshCallback
			},
			element: element
		});
	}
});